﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Net.Configuration;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using SAS.Bussiness;
using SAS.Core;
using SAS.Core.Entity;
using SAS.Core.Result;

namespace SAS.WebSite.Service
{
    public partial class Services
    {
        /*The services for workspaces*/
        [WebMethod]
        public static string GetWorkspaces(string seid, object json, object search)
        {

            #region validate

            //validate inputted parameters
            if (string.IsNullOrEmpty(seid) || json == null)
                return string.Empty;

            #endregion

            //parse json data to objects
            AdvSearch advSearch = GetAdvanceSearch(json);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strsearch = serializer.Serialize(search);
            SearchParameters advsrch = serializer.Deserialize<SearchParameters>(strsearch);

            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
                {
                    FromIP = ClientIp
                };
            SASResult<IList<WorkspaceSummary>> bussinessResult = workspaceBo.GetWorkspaces(User, advSearch, advsrch);

            //serialize object data to json
            var jsonObject = new
            {
                page = bussinessResult.OutputResult["PageNumber"],
                total = bussinessResult.OutputResult["PageSize"],
                records = bussinessResult.OutputResult["ResultCount"],
                rows = bussinessResult.Result,
                errorMessage = bussinessResult.Message
            };

            //return service call
            return serializer.Serialize(jsonObject);
        }

        [WebMethod]
        public static string GetWorkspace(string seid, object key, object intrnl)
        {
            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
                {
                    FromIP = ClientIp
                };
            SASResult<WorkspaceDetail> bussinessResult = workspaceBo.GetWorkspace(User, Convert.ToString(key));

            //serialize object data to json
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            object wpLastModifyDate = bussinessResult.Result == null || bussinessResult.Result.Workspace.WSModifiedDate == DateTime.MinValue
                                          ? String.Empty
                                          : bussinessResult.Result.Workspace.WSModifiedDate.ToString(CultureInfo.InvariantCulture);

            object wpCreateDate = bussinessResult.Result == null
                                      ? String.Empty
                                      : bussinessResult.Result.Workspace.CreatedDate.ToString(CultureInfo.InvariantCulture);

            //define json object return
            var jsonObject = new
            {
                //Workspace data
                wp = bussinessResult.Result == null ? (object)String.Empty : bussinessResult.Result.Workspace,
                //Client data
                client = bussinessResult.Result == null ? (object)String.Empty : bussinessResult.Result.Client,
                //Client connection data
                clientIO = bussinessResult.Result == null ? (object)String.Empty : bussinessResult.Result.ClientIOFile,
                //Base64 logo image string
                logo = bussinessResult.Result == null ? (object)String.Empty : bussinessResult.Result.ImageLogo,
                //workspace create date
                workspaceCreateDate = wpCreateDate,
                //workspace modify date
                workspaceModifyDate = wpLastModifyDate,
                //error message
                errorMessage = bussinessResult.Message,
            };

            return serializer.Serialize(jsonObject);
        }

        [WebMethod]
        public static string GetEnvironment()
        {
            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
            {
                FromIP = ClientIp
            };
            SASResult<IList<string>> userRoles = workspaceBo.GetEnvironmentNames(User);

            var jsonObject = new
            {
                dropDownItem = userRoles.Result,
                errorMessage = userRoles.Message
            };

            //serialize and return json message
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strSerializedString = serializer.Serialize(jsonObject);
            return strSerializedString;
        }

        [WebMethod]
        public static string CreateCloneSavedWorkspace(string seid, string workspaceId)
        {  

            //get the physical web path.
            string webPhysicalPath = Path.GetDirectoryName(HttpContext.Current.Request.MapPath(""));

            //get default logo path.
            string defaultLogo = ConfigurationManager.AppSettings.Get("DefaultLogo");

            //locate default logo.
            string defaultLogoPath = String.Format(@"{0}\{1}", webPhysicalPath, defaultLogo);

            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
            {
                FromIP = ClientIp
            };

            SASResult<String> cloningResult = workspaceBo.Cloning(User, workspaceId, defaultLogoPath);

            var jsonObject = new
            {
                dropDownItem = cloningResult.Result,
                errorMessage = cloningResult.Message
            };

            //serialize and return json message
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strSerializedString = serializer.Serialize(jsonObject);
            return strSerializedString;
        }

        [WebMethod]
        public static string SendAdminInfo(string seid, object json)
        {
            
            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
            {
                FromIP = ClientIp
            };

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strjson = serializer.Serialize(json);

            DefaultAdminInfo defaultAdminInfo = serializer.Deserialize<DefaultAdminInfo>(strjson);

            //Read web configuration.
            Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);

            //Read mail setting configuration.
            MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

            //get the physical web path.
            string webPhysicalPath = System.IO.Path.GetDirectoryName(HttpContext.Current.Request.MapPath(""));

            //get active email template path.
            string emailTemplatePath = ConfigurationManager.AppSettings.Get("ActiveWorkspaceEmailTemplate");

            //locate activate email template.
            string templatePath = String.Format(@"{0}\{1}", webPhysicalPath, emailTemplatePath);

            //send mail
            SASResult<bool> sendEmailResult = workspaceBo.SendDefaultAdminInfomation(User, settings, templatePath, defaultAdminInfo);

            var jsonObject = new
            {
                sendResult = sendEmailResult.Result,
                errorMessage = sendEmailResult.Message
            };

            string strSerializedString = serializer.Serialize(jsonObject);
            return strSerializedString;
        }

        [WebMethod]
        public static string ValidateActiveClientId(string seid, string clientId, string targetEnvironment)
        {
            
            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
            {
                FromIP = ClientIp
            };

            SASResult<bool> validateResult = workspaceBo.ValidateActiveClientId(User, clientId, targetEnvironment);

            var jsonObject = new
            {
                validateResult = validateResult.Result,
                errorMessage = validateResult.Message
            };

            //serialize and return json message
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strSerializedString = serializer.Serialize(jsonObject);
            return strSerializedString;
        }

        [WebMethod]
        public static string ValidateCreateWorkspaceName(string seid, string workspaceName)
        {
            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
            {
                FromIP = ClientIp
            };

            SASResult<bool> validateResult = workspaceBo.ValidateInsertWorkspaceName(User, workspaceName);
            var jsonObject = new
            {
                validateResult = validateResult.Result,
                errorMessage = validateResult.Message
            };

            //serialize and return json message
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strSerializedString = serializer.Serialize(jsonObject);
            return strSerializedString;
        }

        [WebMethod]
        public static string ValidateCreateClientId(string seid, string clientId)
        {
            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
            {
                FromIP = ClientIp
            };

            SASResult<bool> validateResult = workspaceBo.ValidateInsertClientId(User, clientId);
            var jsonObject = new
            {
                validateResult = validateResult.Result,
                errorMessage = validateResult.Message
            };

            //serialize and return json message
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strSerializedString = serializer.Serialize(jsonObject);
            return strSerializedString;
        }

        [WebMethod]
        public static string ValidateActivateClientShortName(string clientShortName, string targetEnvironment)
        {
            
            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
                {
                    FromIP = ClientIp
                };
            SASResult<bool> validateResult = workspaceBo.ValidateActivateClientShortName(User, clientShortName, targetEnvironment);

            var jsonObject = new
            {
                validateResult = validateResult.Result,
                errorMessage = validateResult.Message
            };

            //serialize and return json message
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strSerializedString = serializer.Serialize(jsonObject);
            return strSerializedString;
        }

        [WebMethod]
        public static string ValidateUpdateWorkspaceName(string seid, string workspaceId, string workSpaceName)
        {
            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
            {
                FromIP = ClientIp
            };
            SASResult<bool> validateResult = workspaceBo.ValidateUpdateWorkspaceName(User, workspaceId, workSpaceName);

            var jsonObject = new
            {
                validateResult = validateResult.Result,
                errorMessage = validateResult.Message
            };

            //serialize and return json message
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strSerializedString = serializer.Serialize(jsonObject);
            return strSerializedString;
        }

        [WebMethod]
        public static string ActivateCloneSavedWorkspace(string seid, object activateInfo)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strjson = serializer.Serialize(activateInfo);

            ActiavateCloneSaveWorkspace actiavateCloneSaveWorkspace = serializer.Deserialize<ActiavateCloneSaveWorkspace>(strjson);
            
            return string.Empty;
        }

        [WebMethod]
        public static string ValidateUpdateClientShortName(string seid, string clientId, string clientShortName, string targetEnvironment)
        {
            //call to business layer to get the data
            WorkspaceBO workspaceBo = new WorkspaceBO
            {
                FromIP = ClientIp
            };
            SASResult<bool> validateResult = workspaceBo.ValidateUpdateClientShortName(User, clientId, targetEnvironment, clientShortName);

            var jsonObject = new
            {
                validateResult = validateResult.Result,
                errorMessage = validateResult.Message
            };

            //serialize and return json message
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strSerializedString = serializer.Serialize(jsonObject);
            return strSerializedString; 
        }
    }
}